package com.monitorStudy.config;

import io.prometheus.client.Counter;
import org.omg.CORBA.UserException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author: Alan
 * @date: 2021/5/13 21:27
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    @Autowired
    AppConfig appConfig;

    public static final Counter counterDemo = Counter.build()
            .name("push_error_counter")
            .labelNames("msg", "instance")
            .help("service异常统计")
            .register();

    /**
     * 传入msg做异常统计
     * @param msg
     */
    private void pushData(String msg) {
        //指标值增加
        counterDemo.labels(msg, appConfig.getApplicationName()).inc();
        try {
            PrometheusConfig.prometheusPush.push(counterDemo, "push_error_counter");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 用戶模塊全局異常信息處理
     * @param err
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String handleUserException(HttpServletRequest request, UserException err) {
        pushData(err.getMessage());
        return "errorInfo";
    }
}
